package com.aliyun.iot.demo.iothub;

import java.util.Map;

import org.apache.commons.codec.binary.Base64;

import com.alibaba.fastjson.JSON;
import com.aliyun.mns.client.CloudAccount;
import com.aliyun.mns.client.CloudQueue;
import com.aliyun.mns.client.MNSClient;
import com.aliyun.mns.model.Message;

/**
 * https://help.aliyun.com/document_detail/68948.html?spm=a2c4g.11174283.6.552.KTp0Ba
 * 
 * @author zhilin
 *
 */
public class TestMNS {
	private final static  String  AccessKeyId= "";
	private final static  String  AccessKeySecret= "";
	private final static  String  AccountEndpoint= "";
	
	
	public static void main(String[] args) {
	CloudAccount account = new CloudAccount(
                AccessKeyId,
                AccessKeySecret,
                AccountEndpoint);
		MNSClient client = account.getMNSClient();
		//参数请输入IoT自动创建的队列名称，例如上面截图中的aliyun-iot-3AbL0062osF
		CloudQueue queue = client.getQueueRef("aliyun-iot-a1NcRC0sKf8"); 
		while (true) {
			String jsonStr ="";
			Message popMsg= null;
		    try {
				// 获取消息
				 popMsg = queue.popMessage(10); //长轮询等待时间为10秒
				if (popMsg != null) {
					jsonStr = popMsg.getMessageBodyAsString();
					Map map = JSON.parseObject(jsonStr, Map.class);
					String payload = (String)map.get("payload");
					byte[] base64Byte = Base64.decodeBase64(payload);
					String data = new String(base64Byte);
					boolean a = data.contains("wyk123");
					System.out.println(a);
					System.out.println(data);
					//获取原始消息
//				    System.out.println("PopMessage Body: " + popMsg.getMessageBodyAsRawString()); 
				    //从队列中删除消息
				    queue.deleteMessage(popMsg.getReceiptHandle());
				} else {
				    System.out.println("Continuing");
				}
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println(jsonStr);
				queue.deleteMessage(popMsg.getReceiptHandle());
			}
		}
	}
	
}
